const router = require('koa-router')()
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const stats = require('../helpers/stats')
const popular = require('../helpers/images')
const newestComments = require('../helpers/comments')

router.get('/', async (ctx, next) => {
  let num = await Image.count()
  if(num > 0){
        await Promise.all([
          Image.find().sort({timestamp: -1}),
          stats(),
          popular(),
          newestComments()
        ])
          .then( ([images, stats, popular, newestComments]) => ctx.render('index',
          {images, stats, popular, newestComments}
        ))
          .catch(err => ctx.throw(500, err))
        }else {
          let images = []
          let stats = {images:0, views:0, likes:0, comments:0}
          let popular = []
          let newestComments = []
          await ctx.render('index',{images, stats, popular, newestComments})
        }
  })

module.exports = router
